package com.dagger.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.dagger.config.MsgConfig;
import com.dagger.constants.LocalErrorCode;
import com.dagger.domain.req.WsMsgReq;
import com.dagger.enums.MsgOptionEnum;
import com.dagger.enums.MsgTypeEnum;
import com.dagger.utils.AbstractMsgUtil;
import com.dagger.utils.ValidateUtils;

/**
 * sse客户端注册
 * @author dagger
 *
 */
@RestController
@RequestMapping("sse")
public class SSEMessageController{

	/**
	 * 
	 * @param msgType 消息类型：DELAY（延时消息），REALTIME（实时消息）
	 * @param bussinessType 业务类型，需要在nacos中配置，区分大小写
	 * @param bussinessIds 业务ID，支持英文逗号分隔
	 * @return
	 */
	@GetMapping(value = { "/client/{msgType}/{bussinessType}/{bussinessIds}" })
	public SseEmitter connectClient(@PathVariable MsgTypeEnum msgType, @PathVariable String bussinessType,
			@PathVariable String bussinessIds) {
		ValidateUtils.validateEmptyEveryone(msgType, bussinessType, bussinessIds);

		if (!MsgConfig.getInstance().contains(bussinessType)) {
			throw new RuntimeException(LocalErrorCode.MSG_NOT_SUPPORT);
		}

		WsMsgReq req = new WsMsgReq();
		req.setBussinessType(bussinessType);
		req.setBussinessId(bussinessIds);
		req.setMsgType(msgType);
		req.setMsgOption(MsgOptionEnum.SUBSCRIBE);

		SseEmitter sseEmitter = AbstractMsgUtil.getSseEmitterUtil().connect();
		String bussinessIdArray[] = req.getBussinessId().trim().split(",");
		switch (req.getMsgType()) {
		case DELAY: {
			for (String bussinessId : bussinessIdArray) {
				AbstractMsgUtil.getSseEmitterUtil().subcribeDelayMsg(sseEmitter, req.getBussinessType(), bussinessId);
			}
			break;
		}
		case REALTIME: {
			for (String bussinessId : bussinessIdArray) {
				AbstractMsgUtil.getSseEmitterUtil().subcribeRealtimeMsg(sseEmitter, req.getBussinessType(),
						bussinessId);
			}
		}
		default:
			throw new RuntimeException(LocalErrorCode.MSG_NOT_SUPPORT);
		}

		return sseEmitter;

	}
}
